<template>
  <div>
    <div v-permission="`/periodStatus:get`" class="grid grid-cols-5 gap-x-4">
      <template v-for="(item, index) in list" :key="index">
        <div class="stage-item" :class="{ begin: item.isBegin }">
          <div
            class="stage-status"
            :style="{ background: item.info ? statusColor(item.info.periodStatusDict) : '#FCDF7E' }"
          >
            <div class="stage-label">{{ item.label }}</div>
            <n-icon
              v-if="
                (item.info && hasPermission('/periodStatus:update')) ||
                (!item.info && hasPermission('/periodStatus:add'))
              "
              :component="ModeEditOutlined"
              class="cursor-pointer"
              @click="handleStage(item, item.info ? 'edit' : 'add')"
            ></n-icon>
          </div>
          <div
            class="stage-content"
            :class="{ 'cursor-pointer': item.info }"
            @click="handleStage(item, item.info ? 'view' : null)"
          >
            <div v-if="item.info" class="stage-info">
              <div class="stage-desc">
                <n-ellipsis class="break-all" :line-clamp="2" :tooltip="false">
                  {{ item.info.record }}
                </n-ellipsis>
              </div>
              <div class="stage-handle">
                <div class="stage-time">{{ $format(item.info.updateTime) }}</div>
                <div class="stage-user">{{ item.info.userName }}</div>
              </div>
            </div>
            <div v-else class="no-fill">暂未填写</div>
          </div>
        </div>
      </template>
    </div>
    <MyDrawer ref="$form" :model-form="model" :disabled="type === 'view'" @submit="handleSubmit">
      <n-form-item label="状态" path="periodStatusDict">
        <AsyncSelect
          v-model:value="model.periodStatusDict"
          value-key="code"
          label-key="name"
          :options="statusOptions"
        />
      </n-form-item>
      <n-form-item label="描述" path="record">
        <n-input
          v-model:value="model.record"
          clearable
          :maxlength="600"
          show-count
          type="textarea"
          :autosize="{
            minRows: 5,
          }"
        />
      </n-form-item>
      <n-form-item label="上传附件" path="refFileDtoList">
        <FileUpload v-model="model.refFileDtoList" />
      </n-form-item>
    </MyDrawer>
  </div>
</template>
<script setup lang="jsx">
import { usePermissionStore } from '@/store'
import { getSelArrDicts } from '@/api/dict'
import { useCrudPro } from '@/hooks/useCrudPro'
import { ModeEditOutlined } from '@vicons/material'
import * as projectApi from '@/api/project'
defineOptions({ name: 'StageStatus' })
const props = defineProps({
  detail: {
    type: Object,
    default: () => ({}),
  },
})
const emits = defineEmits('reset')
const { hasPermission } = usePermissionStore()
const list = ref([
  { label: '项目启动', code: 'START_PROJECT' },
  { label: '排期表确认', code: 'SCHEDULE_CONFIRM' },
  { label: '原型内部确认', code: 'PROTOTYPE_INNER_CONFIRM' },
  { label: '原型客户确认', code: 'PROTOTYPE_CUSTOMER_CONFIRM' },
  { label: '需求文档客户确认', code: 'REQUIREMENT_CUSTOMER_CONFIRM' },
  { label: '设计风格稿确认', code: 'DESIGN_STYLE_CONFIRM', isBegin: true },
  { label: '设计稿内部确认', code: 'DESIGN_INNER_CONFIRM' },
  { label: '设计稿客户确认', code: 'DESIGN_CUSTOMER_CONFIRM' },
  { label: '开发架构内部确认', code: 'DEV_INNER_CONFIRM', isBegin: true },
  { label: '内部提测', code: 'TEST_INNER_SUBMIT', isBegin: true },
  { label: '内部测试通过', code: 'TEST_INNER_SUBMIT_PASS' },
  { label: '客户提测', code: 'TEST_CUSTOMER_SUBMIT' },
  { label: '客户测试通过', code: 'TEST_CUSTOMER_SUBMIT_PASS' },
  { label: '部署上线', code: 'DEPLOY_ONLINE' },
  { label: '验收通过', code: 'ACCEPT_PASS', isBegin: true },
  { label: '开始运维', code: 'START_MAINTENANCE' },
  { label: '结束运维', code: 'END_MAINTENANCE' },
])
async function getStageList() {
  const res = await projectApi.stageList(props.detail.id)
  list.value = list.value.map((item) => ({
    ...item,
    info: res.data.find((val) => val.period === item.code),
  }))
}
const statusOptions = ref([])
async function getStatusOptions() {
  const res = await getSelArrDicts({ codes: 'PERIOD_STATUS' })
  statusOptions.value = res.data.PERIOD_STATUS
}
const statusColor = computed(() => (status) => {
  return statusOptions.value?.find((item) => item.code === status)?.color || '#FCDF7E'
})
const current = ref({})
const callBack = () => {
  $form.value.setState('title', `阶段：${current.value.label}`)
}
function handleStage(item, type) {
  current.value = item
  if (type === 'add') {
    handleAdd(callBack)
  } else if (type === 'edit') {
    handleEdit(item.info, callBack)
  } else if (type === 'view') {
    handleView(item.info, callBack)
  }
}
const { type, model, $form, handleAdd, handleEdit, handleSubmit, handleView } = useCrudPro({
  name: '风险',
  initForm: {
    id: null,
    periodStatusDict: null,
    record: null,
    refFileDtoList: [],
  },
  apis: {
    add: (params) =>
      projectApi.stageAdd({ ...params, projectId: props.detail.id, period: current.value.code }),
    edit: (params) =>
      projectApi.stageEdit({ ...params, projectId: props.detail.id, period: current.value.code }),
  },
  handleChange() {
    $message.success(`（阶段：${current.value.label}）设置成功!`)
    getStageList()
    if (['START_PROJECT', 'START_MAINTENANCE', 'END_MAINTENANCE'].includes(current.value.code)) {
      emits('reset')
    }
  },
})
watch(
  () => props.detail.id,
  (val) => {
    if (hasPermission('/periodStatus:get') && val) {
      getStageList()
    }
  },
  {
    immediate: true,
  }
)
onBeforeMount(() => {
  getStatusOptions()
})
</script>
<style lang="scss" scoped>
.stage-item {
  &.begin {
    grid-column: 1/2;
  }
  .stage-status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 40px;
    border-radius: 4px;
    padding: 0 12px;
    color: #3a3e45;
    font-size: 14px;
  }
  .stage-content {
    height: 160px;
    box-sizing: border-box;
    padding: 16px 12px;
    .no-fill {
      color: #3a3e45;
      font-size: 14px;
    }
    .stage-info {
      display: flex;
      flex-direction: column;
      gap: 14px;
      .stage-desc {
        color: #3a3e45;
        font-size: 14px;
      }
      .stage-handle {
        display: flex;
        align-items: center;
        gap: 12px;
        color: #686f7c;
        font-size: 14px;
      }
    }
  }
}
</style>
